package main

import (
	"time"

	"gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"
)

type Chapter struct {
	ID         bson.ObjectId `bson:"_id,omitempty" json:"id"`
	Index      int           `bson:"index,omitempty" json:"index"`
	Name       string        `bson:"name,omitempty" json:"name"`
	Content    string        `bson:"content" json:"content"`
	Summary    string        `bson:"summary" json:"summary"`
	BookId     bson.ObjectId `bson:"bookId" json:"bookId"` // 关联书籍名称
	CreateTime time.Time     `bson:"createTime" json:"createTime"`
	UpdateTime time.Time     `bson:"updateTime" json:"updateTime"`
}

func chapterCollection() *mgo.Collection {
	return GetSession().DB("mybook").C("chapters")
}

// 创建章节
func CreateChapter(chapter *Chapter) error {

	chapter.CreateTime = time.Now()
	chapter.UpdateTime = time.Now()
	return chapterCollection().Insert(chapter)
}

// 获取单个章节
func GetChapter(id string) (*Chapter, error) {
	if !bson.IsObjectIdHex(id) {
		return nil, mgo.ErrNotFound
	}

	var chapter Chapter
	err := chapterCollection().FindId(bson.ObjectIdHex(id)).One(&chapter)
	return &chapter, err
}

// 更新章节
func UpdateChapter(id string, updateData bson.M) error {
	if !bson.IsObjectIdHex(id) {
		return mgo.ErrNotFound
	}
	updateData["updateTime"] = time.Now()
	return chapterCollection().UpdateId(bson.ObjectIdHex(id), bson.M{"$set": updateData})
}

// 删除章节
func DeleteChapter(id string) error {
	if !bson.IsObjectIdHex(id) {
		return mgo.ErrNotFound
	}
	return chapterCollection().RemoveId(bson.ObjectIdHex(id))
}

// 删除书藉的所有章节
func DeleteChaptersByBook(bookID string) error {
	if !bson.IsObjectIdHex(bookID) {
		return mgo.ErrNotFound
	}
	_, err := chapterCollection().RemoveAll(bson.M{"bookId": bson.ObjectIdHex(bookID)})
	return err
}

// 获取用户的所有章节
func GetChaptersByUser(userID string) ([]Chapter, error) {
	var chapters []Chapter
	err := chapterCollection().Find(bson.M{"userId": userID}).All(&chapters)
	return chapters, err
}

// 获取书籍与用户的章节，分页查询,同时获得章节总数
func GetChaptersList(bookID string, page, pageSize int) ([]Chapter, int, error) {
	var chapters []Chapter
	skip := (page - 1) * pageSize
	total, err := chapterCollection().Find(bson.M{
		"bookId": bson.ObjectIdHex(bookID),
	}).Count()
	if err != nil {
		return chapters, 0, err
	}
	err = chapterCollection().Find(bson.M{
		"bookId": bson.ObjectIdHex(bookID),
	}).Sort("index").Skip(skip).Limit(pageSize).All(&chapters)
	return chapters, total, err
}
func GetChaptersByBookLast(bookID string, limit int) ([]Chapter, error) {
	if !bson.IsObjectIdHex(bookID) {
		return nil, mgo.ErrNotFound
	}

	var chapters []Chapter
	err := chapterCollection().Find(bson.M{
		"bookId": bson.ObjectIdHex(bookID),
	}).Sort("-index").Limit(limit).All(&chapters)
	return chapters, err
}
